package br.com.simora.fingerprint;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.observer.upload.UploadSizeLimit;
import br.com.caelum.vraptor.observer.upload.UploadedFile;
import br.com.simora.component.HttpTools;
import br.com.simora.controller.BasicController;

import com.google.gson.Gson;
import com.google.gson.JsonPrimitive;

@Controller
public class FingerprintController extends BasicController {
	Logger log = Logger.getLogger(FingerprintController.class);

	public FingerprintController(Result result, ResourceBundle bundle) {
    	this.result = result;
		this.bundle = bundle;
	}

    public FingerprintController(){}
    
	@PostConstruct
    public void init(){
        injetaUsuario();
    }
	
	@Path(value = "/fingerprint")
    @Get
	public void fingerprint(){}
	
	@Path(value = "/fingerprint/gravar")
    @Post
    @UploadSizeLimit(sizeLimit=40 * 1024 * 1024, fileSizeLimit=10 * 1024 * 1024)
	public void gravar(String artista, String musica, UploadedFile file){
		byte[] imgDataBa = new byte[(int)file.getSize()];
		DataInputStream dataIs = new DataInputStream(file.getFile());
		try {
			dataIs.readFully(imgDataBa);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Arquivo arq = new Arquivo();
		JsonPrimitive prim = new JsonPrimitive(Base64.encodeBase64String(imgDataBa));
		arq.setFile(prim);
		arq.setArtist(artista);
		arq.setTitle(musica);
		Gson gson = new Gson();
		String teste = gson.toJson(arq);
		HttpTools tools = new HttpTools();
		String retorno = tools.sendPostJson("http://172.31.37.25:8000/songs/fingerprint/", teste);
		log.debug(retorno);
		//log.debug(teste);
		System.out.println(retorno);
		//System.out.println(teste);
		redirect();
	}
	
	@Override
	protected void redirect() {
		result.redirectTo(FingerprintController.class).fingerprint();
	}

}